package cn.com.pc.content.service;

import cn.com.pc.content.domain.Site;
import cn.com.pc.content.domain.authority.SiteOperator;
import cn.com.pc.content.domain.authority.SiteOperatorRepository;
import cn.com.pc.content.dto.PageResult;
import cn.com.pc.content.dto.SiteOperatorDTO;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class SiteOperatorService {

    private final SiteOperatorRepository repository;


    public SiteOperatorService(SiteOperatorRepository repository) {
        this.repository = repository;
    }


    public boolean isSiteOperator(Site site, long operatorId) {
        return repository.existsByOperatorIdAndSiteAndDeleted(operatorId, site, false);
    }


    public SiteOperator createSiteOperator(SiteOperator siteOperator) {
        if (this.isSiteOperator(siteOperator.getSite(), siteOperator.getOperatorId())) {
            throw new DuplicateKeyException(String.format("%s entity with site %s operatorId %s already exists!", SiteOperator.class, siteOperator.getSite(), siteOperator.getOperatorId()));
        }
        return repository.save(siteOperator);
    }


    public void deleteSiteOperator(Long siteOperatorId) {
        SiteOperator siteOperator = repository.findById(siteOperatorId).orElseThrow(() -> new EmptyResultDataAccessException(
                String.format("No %s entity with id %s exists!", SiteOperator.class, siteOperatorId), 1));
        siteOperator.setDeleted(true);
        repository.save(siteOperator);
    }


    public PageResult<SiteOperatorDTO> listSiteOperators(Site site, int page, int size) {
        return PageResult.getDtoFromPage(repository.findAllBySiteAndDeleted(site, false, PageRequest.of(page - 1, size)), SiteOperatorDTO::from);
    }

}
